package com.njzxw.fs.commonutil.imp;

import com.njzxw.fs.commonutil.bean.FileBean;
import com.njzxw.fs.commonutil.interfaces.OssUtilInterface;
import com.njzxw.fs.commonutil.repository.BaseRep;
import com.njzxw.fs.commonutil.util.DateUtil;
import com.njzxw.fs.commonutil.util.FileHellp;
import com.njzxw.fs.commonutil.util.FtpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class LocalOssImp extends OssUtilAbs{

    @Autowired
    private BaseRep baseRep;

    @Autowired
    private FtpUtils ftpUtils;

    @Override
    public boolean connect() {
        return true;
    }

    @Override
    public FileBean saveTemp(InputStream inputStream,String name,long size) {
        FileBean fileBean = exeName(name,size);
        if(fileBean == null){
            logger.warn("文件丢失");
            return null;
        }
        String filesdir = DateUtil.getToday("yyyyMMddHHmmss")+"_"+new Random().nextInt(100000);
        String dirs = common.getSystem("RESOURCE.TEMP.PATH")+"/"+ filesdir;

        String path = System.getProperty("user.dir");

        String dir = path+dirs;

        if(fileBean.getImg_host().endsWith("/")){
            fileBean.setImg_host(fileBean.getImg_host()+filesdir+"/");
        }else{
            fileBean.setImg_host(fileBean.getImg_host()+"/"+filesdir);
        }

        boolean truth = FileHellp.saveFile(inputStream,dir,fileBean.getFile_name());
        logger.debug("上传truth:"+truth);
        if(!truth){
            return null;
        }

        int exc = baseRep.insertTemp(fileBean);

        if(exc == 1){
            return fileBean;
        };

        return null;
    }

    @Override
    public boolean close() {
        return true;
    }

    @Override
    public String exeFile(String id, String path) {
        FileBean fileBean = baseRep.getTempFile(id);
        logger.debug("fileBean:"+fileBean);
        if(StringUtils.isBlank(fileBean.getFile_name())){
            return "";
        }


        String fileUrlPathLocal = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
        //先到本地获取，如果本地能获取到不走网络配置
        logger.debug("fileUrlPathLocal:"+fileUrlPathLocal);
        String dirs = fileUrlPathLocal.substring(fileUrlPathLocal.indexOf(common.getSystem("RESOURCE.TEMP.PATH")));

        String path_ = System.getProperty("user.dir");

        String dir = path_+dirs;

        logger.debug("dir:"+dir);

        //临时下载文件
        URL url = null;
        InputStream inputStream = null;
        try {

            File file = new File(dir);

            if(file.exists()){
                inputStream = new FileInputStream(file);
            }else{
                String fileUrlPath = (fileBean.getImg_host()+fileBean.getFile_name());
                System.out.println("fileUrlPath:"+fileUrlPath);
                url = new URL(fileUrlPath);
                // 打开连接
                URLConnection con = url.openConnection();
                //设置请求超时为10s
                con.setConnectTimeout(10 * 1000);
                inputStream = con.getInputStream();
            }

            fileBean.setImg_host(common.getSystem("RESOURCE.IMGHOST")+path+"/");
            fileBean.setPath(path);

            String toDir = path_+common.getSystem("LOCALHOST.PATH")+path+"/";

            File toDirFile = new File(toDir);
            if(!toDirFile.exists()){
                toDirFile.mkdirs();
            }
            logger.debug("拷贝路径："+toDir+fileBean.getFile_name());
            File toFile = new File(toDir,fileBean.getFile_name());

            if(FileHellp.copyFile(toFile,inputStream)){
                if(baseRep.insertFile(fileBean) != 1){
                    return null;
                }
                return String.valueOf(fileBean.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
//            ftpUtils.disconnect();
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return "";
    }

    @Override
    public String exeFile(String id, String path, String oper_id, int oper_type, String oper_name) {
        if(id.startsWith("z")){//已经在正式中存在，直接下一个

            return id.replace("z","");
        }
        FileBean fileBean = baseRep.getTempFile(id);
        logger.debug("fileBean:"+fileBean);
        if(StringUtils.isBlank(fileBean.getFile_name())){
            return "";
        }

        String fileUrlPathLocal = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
        //先到本地获取，如果本地能获取到不走网络配置
        logger.debug("fileUrlPathLocal:"+fileUrlPathLocal);
        String dirs = fileUrlPathLocal.substring(fileUrlPathLocal.indexOf(common.getSystem("RESOURCE.TEMP.PATH")));

        String path_ = System.getProperty("user.dir");

        String dir = path_+dirs;

        logger.debug("dir:"+dir);

        //临时下载文件
        URL url = null;
        InputStream inputStream = null;
        try {

            File file = new File(dir);

            if(file.exists()){

                inputStream = new FileInputStream(file);
            }else{
                String fileUrlPath = (fileBean.getImg_host()+fileBean.getFile_name());
                System.out.println("fileUrlPath:"+fileUrlPath);
                url = new URL(fileUrlPath);
                // 打开连接
                URLConnection con = url.openConnection();
                //设置请求超时为10s
                con.setConnectTimeout(10 * 1000);
                inputStream = con.getInputStream();
            }

            fileBean.setImg_host(common.getSystem("RESOURCE.IMGHOST")+path+"/");
            fileBean.setPath(path);
            fileBean.setOper_name(oper_name);
            String toDir = path_+common.getSystem("LOCALHOST.PATH")+path+"/";

            File toDirFile = new File(toDir);
            if(!toDirFile.exists()){
                toDirFile.mkdirs();
            }
            logger.debug("拷贝路径："+toDir+fileBean.getFile_name());
            File toFile = new File(toDir,fileBean.getFile_name());

            fileBean.setOper_id(oper_id);
            fileBean.setOper_type(oper_type);
            if(FileHellp.copyFile(toFile,inputStream)){
                if(baseRep.insertFile(fileBean) != 1){
                    return null;
                }
                return String.valueOf(fileBean.getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
//            ftpUtils.disconnect();
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return "";
    }

    @Override
    public List<String> exeFile(List<String> ids, String path) {

        List<String> returnList = new ArrayList<>();
        try{
//            if(!ftpUtils.initFtpClient()){
//                return null;
//            }

            for(int i=0;i<ids.size();i++){
                String id = ids.get(i);
                FileBean fileBean = baseRep.getTempFile(id);
                logger.debug("fileBean:"+fileBean);
                if(StringUtils.isBlank(fileBean.getFile_name())){
                    return null;
                }

                String fileUrlPathLocal = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
                //先到本地获取，如果本地能获取到不走网络配置
                String dirs = fileUrlPathLocal.substring(fileUrlPathLocal.indexOf(common.getSystem("RESOURCE.TEMP.PATH")));

                String path_ = System.getProperty("user.dir");

                String dir = path_+dirs;

                logger.debug("dir:"+dir);

                URL url = null;

                InputStream inputStream = null;
                try{
                    logger.debug("dir:"+dir);
                    File file = new File(dir);

                    if(file.exists()){

                        inputStream = new FileInputStream(file);
                    }else{
                        String fileUrlPath = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
                        System.out.println("fileUrlPath:"+fileUrlPath);
                        url = new URL(fileUrlPath);
                        // 打开连接
                        URLConnection con = url.openConnection();
                        //设置请求超时为10s
                        con.setConnectTimeout(10 * 1000);
                        inputStream = con.getInputStream();
                    }

                    fileBean.setImg_host(common.getSystem("RESOURCE.IMGHOST")+path+"/");
                    fileBean.setPath(path);

                    String toDir = path_+common.getSystem("LOCALHOST.PATH")+path;

                    File toDirFile = new File(toDir);
                    if(!toDirFile.exists()){
                        toDirFile.mkdirs();
                    }
                    logger.debug("拷贝路径："+toDir+fileBean.getFile_name());
                    File toFile = new File(toDir,fileBean.getFile_name());

                    if(FileHellp.copyFile(toFile,inputStream)){
                        if(baseRep.insertFile(fileBean) != 1){
                            return null;
                        }
                        returnList.add(String.valueOf(fileBean.getId()));
                    }

//                    if(ftpUtils.uploadFile(path,fileBean.getFile_name(),inputStream)){
//                        if(baseRep.insertFile(fileBean) != 1){
//                            return null;
//                        }
//                        returnList.add(String.valueOf(fileBean.getId()));
//                    }

                }catch (Exception e){
                    logger.error("文件正式存储失败：",e);
                    return null;
                } finally {
                    if(inputStream != null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
//                            e.printStackTrace();
                        }
                    }
                }



            }
            return returnList;

        }catch (Exception e){
            logger.error("文件正式存储失败：",e);
            return null;
        }finally {
//            ftpUtils.disconnect();
        }
    }

    @Override
    public List<String> exeFile(List<String> ids, String path,String oper_id,int oper_type,String oper_name) {

        List<String> returnList = new ArrayList<>();
        try{
//            if(!ftpUtils.initFtpClient()){
//                return null;
//            }

            for(int i=0;i<ids.size();i++){
                String id = ids.get(i);
                if(id.startsWith("z")){//已经在正式中存在，直接下一个
                    returnList.add(id.replace("z",""));
                    continue;
                }
                FileBean fileBean = baseRep.getTempFile(id);
                logger.debug("fileBean:"+fileBean);
                if(StringUtils.isBlank(fileBean.getFile_name())){
                    return null;
                }

                String fileUrlPathLocal = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
                //先到本地获取，如果本地能获取到不走网络配置
                String dirs = fileUrlPathLocal.substring(fileUrlPathLocal.indexOf(common.getSystem("RESOURCE.TEMP.PATH")));

                String path_ = System.getProperty("user.dir");

                String dir = path_+dirs;

                logger.debug("dir:"+dir);

                URL url = null;

                InputStream inputStream = null;
                try{
                    logger.debug("dir:"+dir);
                    File file = new File(dir);

                    if(file.exists()){

                        inputStream = new FileInputStream(file);
                    }else{
                        String fileUrlPath = (fileBean.getImg_host()+fileBean.getFile_name()).replaceAll("//","/");
                        System.out.println("fileUrlPath:"+fileUrlPath);
                        url = new URL(fileUrlPath);
                        // 打开连接
                        URLConnection con = url.openConnection();
                        //设置请求超时为10s
                        con.setConnectTimeout(10 * 1000);
                        inputStream = con.getInputStream();
                    }

                    fileBean.setImg_host(common.getSystem("RESOURCE.IMGHOST")+path+"/");
                    fileBean.setPath(path);
                    fileBean.setOper_name(oper_name);
                    String toDir = path_+common.getSystem("LOCALHOST.PATH")+path;

                    File toDirFile = new File(toDir);
                    if(!toDirFile.exists()){
                        toDirFile.mkdirs();
                    }
                    logger.debug("拷贝路径："+toDir+fileBean.getFile_name());
                    File toFile = new File(toDir,fileBean.getFile_name());

                    fileBean.setOper_id(oper_id);
                    fileBean.setOper_type(oper_type);
                    if(FileHellp.copyFile(toFile,inputStream)){
                        if(baseRep.insertFile(fileBean) != 1){
                            return null;
                        }
                        returnList.add(String.valueOf(fileBean.getId()));
                    }

                }catch (Exception e){
                    logger.error("文件正式存储失败：",e);
                    return null;
                } finally {
                    if(inputStream != null){
                        try {
                            inputStream.close();
                        } catch (IOException e) {
//                            e.printStackTrace();
                        }
                    }
                }



            }
            return returnList;

        }catch (Exception e){
            logger.error("文件正式存储失败：",e);
            return null;
        }finally {
//            ftpUtils.disconnect();
        }
    }
}
